//
//  NovelViewController.m
//  ChineseCollegeStudentsNetwork
//
//  Created by 魏苏扬 on 2018/8/8.
//  Copyright © 2018年 刘喆. All rights reserved.
//

#import "NovelViewController.h"

#import "NovelHeaderView.h"
#import "NovelSectionView.h"

#import "IntroductionViewCell.h"
#import "WXApi.h"
#import "NovelModel.h"
#import "NovelCell.h"
#import "NovelDetailVC.h"
#import "AddCartVC.h"
#import "C_CartModel.h"

static NSString *kIntroductionViewCell = @"IntroductionViewCell.h";

@interface NovelViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSArray<NovelModel *> *modelsArr;
@property (nonatomic, strong) NSMutableArray *cartModels;


@end

@implementation NovelViewController
- (instancetype)init {
    self = [super init];
    if (self) {

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];
    self.title = @"免费试读";
    [self setupUI];
    [self setupLayout];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payStatusAction:) name:@"kPayStatusNotification" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];

}

- (void)loadData {
    NSDictionary *param = @{@"articleId":@"0",@"siteId":@"32",@"contentId":_curModel.Id};
    
    [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/SS.Magazine/ApiArticles" params:param.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        NSArray *list = response[@"articles"];
        _modelsArr = [NovelModel mj_objectArrayWithKeyValuesArray:list];
        [self.tableView reloadData];
    } failure:^{
        
    }];
    
    
    [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiCartGet" params:@{@"siteId":@"32"}.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {

//        NSArray *arr = [C_CartModel mj_objectArrayWithKeyValuesArray:response[@"cartInfoList"]];
        _cartModels = [NSMutableArray arrayWithArray:response[@"cartInfoList"]];
        
        
    } failure:^{
        
    }];

}

#pragma mark- UI
- (void)setupLayout{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset = 0;
    }];
}

- (void)setupUI{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 100;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerClass:[IntroductionViewCell class] forCellReuseIdentifier:kIntroductionViewCell];
    [self.tableView registerClass:[NovelCell class] forCellReuseIdentifier:@"kCell_ID"];

    [self.view addSubview:self.tableView];
    
    NovelHeaderView *tableHeaderView = [[NovelHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210)];
    tableHeaderView.obj = self.curModel;
    self.tableView.tableHeaderView = tableHeaderView;
    
    tableHeaderView.buyClickBlock = ^(NSInteger index) {
        [self startPayAction:index];
    };
    
}

#pragma mark - Actions
- (void)startPayAction:(NSInteger)index {
    
    //1.纸质 2.电子
    
    if (index == 2) {
        
        NSDictionary *param = @{@"addressId":@"",
                                @"cartIdList":@"",
                                @"channel":@"app",
                                @"deliveryFee": @"0",
                                @"isMobile": @1,
                                @"message": @20,
                                @"siteId": _curModel.siteId,
                                @"successUrl":@"",
                                @"totalCount": @0,
                                @"totalFee":_curModel.readingCost
                                };
        
        [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiPay" params:param.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"您将购买%@,费用为%@元,去支付?",_curModel.title,_curModel.readingCost] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self postWeiXinPay:response];
            }];
            [alert addAction:act];
            [alert addAction:act1];
            [self presentViewController:alert animated:YES completion:nil];
        } failure:^{
            
        }];
    } else {
        
        
        C_CartModel *addModel = [[C_CartModel alloc] init];
        addModel.addDate = _curModel.addDate;
        addModel.count = @"1";
        addModel.fee = _curModel.paperCost;
        addModel.imageUrl = _curModel.imageUrl;
        addModel.isDelivery = @(true);
        addModel.linkUrl = _curModel.linkUrl;
        addModel.siteId = @"32";

        [_cartModels addObject:addModel.mj_JSONObject];
        
        NSDictionary *param = @{@"siteId":@"32",
                                @"cartInfoList":_cartModels
                                };
        
        [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.shopping/ApiCartSave" params:param.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
            AddCartVC *acVC = [[AddCartVC alloc] init];
            acVC.model = _curModel;
            [self.navigationController pushViewController:acVC animated:YES];
        } failure:^{
            
        }];
    }

}

- (void)postWeiXinPay:(NSDictionary *)param {
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:param];
    [params setObject:@"producta" forKey:@"detail"];
    [MLAHttpManage postHttpType:MLAHttpRequestType_Post hostType:MLAHttpHostType_Api api:@"/api/plugins/ss.magazine/WeiXinPay" params:params.mj_JSONString success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        PayReq* req             = [[PayReq alloc] init];
        req.partnerId           = [response objectForKey:@"partnerid"];
        req.prepayId            = [response objectForKey:@"prepayid"];
        req.nonceStr            = [response objectForKey:@"noncestr"];
        req.timeStamp           = [response[@"timestamp"] intValue];
        req.package             = [response objectForKey:@"packagestr"];
        req.sign                = [response objectForKey:@"sign"];
        [WXApi sendReq:req];
    } failure:^{
        
    }];
}


#pragma mark- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 0 ? 1 : _modelsArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0) {
        IntroductionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kIntroductionViewCell forIndexPath:indexPath];
        cell.title = self.curModel.content;
        return cell;
    } else {
        NovelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kCell_ID" forIndexPath:indexPath];
        cell.model = _modelsArr[indexPath.item];
        return cell;
    }
    
}

#pragma mark- UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NovelSectionView *sectionView = [[NovelSectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    sectionView.title = @[@"商品简介",@"杂志文章列表"][section];
    return sectionView;
}
- (CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NovelModel *model = _modelsArr[indexPath.row];
    if (model.isFree.integerValue == 1) {
        NovelDetailVC *ndVC = [[NovelDetailVC alloc] init];
        ndVC.titleStr = model.title;
        ndVC.contentStr = model.content;
        [self.navigationController pushViewController:ndVC animated:YES];
    } else {
        ShowMessage(@"大学杂志社：改文章为付费文章");
    }
}


#pragma mark
- (void)payStatusAction:(NSNotification *)nofi {
    
    BaseResp *resp = (BaseResp *)nofi.object;
    
     switch (resp.errCode) {
         case WXSuccess:
         {
             [self loadData];
             ShowMessage(@"支付成功");
         }
             break;
     
         default:
         {
             ShowMessage(@"支付失败");
         }
             break;
     }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kPayStatusNotification" object:nil];
}

@end
